package cn.edu.pku.cs08.liudun.picventure.view;

import cn.edu.pku.cs08.liudun.picventure.AppConfig;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class DisplayAreaView extends View {
	private static final String TAG = "DisplayAreaView";
	
	public DisplayAreaView(Context context) {
		super(context);
		init();
	}
	
	public DisplayAreaView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public DisplayAreaView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	private AppConfig appConfig = null;
	private Bitmap displayBmp = null; 
	private Matrix scaleBmpMatrix = null;
	
	public void init() {
		Log.e(TAG, "init");
		appConfig = (AppConfig) this.getContext().getApplicationContext();
		Bitmap b = appConfig.getDisplayBmp();
		if(b != null) {
			init(b);
		}
	}
	
	@Override
	public void onDraw(Canvas canvas) {
//		Log.e(TAG, "onDraw");
		if(displayBmp == null) {
			Log.e(TAG, "null displayBmp");
			return;
		}
		canvas.drawBitmap(this.displayBmp, scaleBmpMatrix, null);
	}
	
	public void init(Bitmap bmp) {
		Log.e(TAG, "init(Bitmap bmp)");
		this.displayBmp = bmp;
		initScaleBmpMatrix();
	}
	
	private void initScaleBmpMatrix() {
		if(displayBmp == null) {
			Log.e(TAG, "updateScaleBmpMatrix: null displayBmp");
			return;
		}
		if(scaleBmpMatrix == null) {
			scaleBmpMatrix = new Matrix();
		}
		scaleBmpMatrix.setRectToRect(
				getDisplayBmpRectF(), 
				appConfig.getScrenRectF(), 
				Matrix.ScaleToFit.CENTER);
	}
	
	private RectF getDisplayBmpRectF() {
		if(displayBmp == null) {
			Log.e(TAG, "getDisplayBmpRectF: null displayBmp");
			return null;
		}
		Log.e(TAG, "getDisplayBmpRectF: " + displayBmp.getWidth() + " " + displayBmp.getHeight());
		return (new RectF(0, 0, displayBmp.getWidth()-1, displayBmp.getHeight()-1));
	}



}
